<template>
	<u-popup v-model="popupVisible" border-radius="16" closeable mode="bottom" safe-area-inset-bottom
		@close="$popupClose">
		<view class="goods-spec-box" :style="{ '--color': vuex_config.themeColor1, '--price': vuex_config.price }"
			v-if="specActItem.pk_id?true:false">
			<view class="prod-info">
				<view class="prod-img">
					<image @click="onPreviewImage(specActItem.img ? specActItem.img : dataForm.logo)" mode="aspectFill"
						:src="$formatImg(specActItem.img ? specActItem.img : dataForm.logo)"></image>
					<template v-if="specActItem.max_num <= 0">
						<view class="no_bg"></view>
						<view class="no_prod">
							<view class="no_box">
								<view class="title">已售罄</view>
							</view>
						</view>
					</template>
				</view>
				<view class="prod-right">
					<view class="">{{dataForm.name}}</view>
					<view class="prod-price">
						<text>价格：</text>
						<text class="u-font-24">￥</text>
						<text class="u-font-36">{{ $price(specActItem.amount) }}</text>
						<!-- 会员价格 -->
						<block v-if="showVip && specActItem.vip_price >= 0">
							<text class="u-m-l-20 sww-tp u-m-r-6">vip</text>
							<text class="u-font-24 sww-tp">￥</text>
							<text class="u-font-34 sww-tp">{{ $price(specActItem.vip_price) }}</text>
						</block>
						<!-- 分销返佣 -->
						<block
							v-else-if="vuex_user.type == 2 && rebate > 0 && specActItem.commission && specActItem.commission.replace('%','') > 0">
							<text class="u-font-26 sww-tp u-m-r-5 u-m-l-20">分享赚</text>
							<text
								class="u-font-26 sww-tp">{{specActItem.commission.includes('%')?$rebateNum(rebate, specActItem.commission.replace('%','')):specActItem.commission }}</text>
						</block>
					</view>
				</view>
			</view>

			<scroll-view scroll-y class="spec_scroll">
				<view class="spec_main">
					<view class="spec_box" v-for="(classItem,classIndex) in classList" :key="classIndex">
						<view class="spec_title">{{classList.length > 1?classItem.name:''}}</view>
						<view class="prod-spec-list">
							<block v-for="(item, index) in typeList[classIndex]" :key="index">
								<view class="prod-spec-item" :class="{ 'disabled':item.disabled,'prod-spec-act': index === classItem.current }"
									@click="$specChange(index,classIndex)">
									<view class="post_dis" v-if="item.disabled">缺货</view>
									<text class="u-line-1">{{ item.name }}</text>
								</view>
							</block>
						</view>
					</view>
				</view>
				<div class="buy_num">
					<view>数量</view>
					<u-number-box v-model="specNum" input-height="54" input-width="104" :min='dataForm.minimum'
						:max="specActItem.max_num">
					</u-number-box>
				</div>
			</scroll-view>
			<view class="sub-bottom">
				<view :class="['goods-action-btn-wrap', specActItem.max_num <= 0 ? 'disabled' : 'usal']">
					<block v-if="params.buyType">
						<view class="goods-action-btn" @click="$submitProd(params.buyType)">确定</view>
					</block>
					<block v-else>
						<view class="goods-action-btn" @click="$submitProd('cart')"><text>加入购物车</text></view>
						<view class="goods-action-btn" @click="$submitProd('buy')"><text>立即购买</text></view>
					</block>
				</view>
			</view>
		</view>
	</u-popup>
</template>
<script>
	import {
		formatStockList
	} from '../../module/product/prodMet';
	import {
		mapActions,
		mapState
	} from 'vuex';

	export default {
		props: {
			detailApi: {
				type: String,
				default: 'GetProductDetailed'
			}, // 查询商品详情
			value: {
				// 绑定弹框显隐
				type: Boolean,
				default: false
			},
			params: {
				// 参数 buyType: 类型,
				type: Object,
				default: () => {
					return {
						buyType: '', //必须 购买方式
						prodId: '', //产品ID type为 1和2时
						stockId: '', //产品规格ID type为1时
						cartId: '', //购物车ID type为1时
						num: 0 //产品规格购买数量 type为1时
					};
				}
			},
			type: {
				// 当前弹框类型
				type: String,
				default: '0' //0 产品详情， 1 购物车切换规格, 2 列表页选择规格
			},
			prodInfo: {
				// 如果已有商品详情，可以传入，否则在弹框调起时会获取
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				popupVisible: false,
				showVip: false, // 是否允许显示并使用会员价格
				dataForm: {
					img_list: [{}]
				},
				specActItem: {},
				specActIndex: -1, 
				specNum: 0,
				classList: [],
				typeList: [],
			};
		},
		computed: {
			...mapState(['vuex_cart_list']),
			rebate() {
				//计算返佣
				return this.specActItem.rebate * this.specNum;
			}
		},
		watch: {
			value(val) {
				if (val) {
					if (this.type == '0') {
						this.$checkInfoByProd();
					} else {
						this.specNum = 0;
						this.specActIndex = -1;
						if (this.type == '1') {
							this.$checkInfoByCart();
						} else if (this.type == '2') {
							this.$checkInfoByList();
						}
					}
				}
			},
			prodInfo(val) {
				if (val && val.pk_id) {
					this.dataForm = {
						...val
					}
					this.specActItem = {}
					this.$checkInfoByProd(true);
				}
			}
		},
		methods: {
			...mapActions(['addProdToCart']),
			//显示弹框
			$showPopup() {
				this.popupVisible = true;
			},
			//关闭弹框
			$popupClose() {
				this.popupVisible = false;
				this.$emit('input', false);
			},
			$checkInfoByProd(noShow) {
				this.$nextTick(() => {
					if (!this.specActItem.pk_id) {
						this.dataForm.product_stock = formatStockList(this.dataForm.product_stock, false, this
							.dataForm.minimum);
						if (this.specActIndex === -1 && this.dataForm.product_stock.length > 0) {
							this.specActIndex = 0;
							this.specActItem = this.dataForm.product_stock[0];
							this.specNum = this.specActItem.min_num;
						} else {
							this.specActItem = this.dataForm.product_stock[this.specActIndex];
							this.specNum = this.specNum <= this.specActItem.max_num ? this.specNum : this
								.specActItem.max_num;
						}
						this.initClassName()
						this.checkVipPrice();
					} // 只需要加载一次就好
					if (!noShow) {
						this.$showPopup();
					}
				});
			},
			$checkInfoByList() {
				this.$nextTick(() => {
					this.$loadProd()
						.then(dataForm => {
							let specActIndex = dataForm.product_stock.findIndex(item => item.min_num > 0);
							if (specActIndex > -1) {
								this.specActIndex = specActIndex;
								this.specActItem = {
									...dataForm.product_stock[specActIndex]
								};
								this.dataForm = {
									...dataForm
								}
								this.specNum = dataForm.product_stock[specActIndex].min_num;
								this.initClassName()
								this.$showPopup();
							} else {
								this.$popupClose();
								this.$toast('库存不足');
							}
							this.checkVipPrice();
						})
						.catch((err) => {
							this.$popupClose();
						});
				});
			},
			$checkInfoByCart() {

				this.$nextTick(() => {
					this.$loadProd(true).then(dataForm => {
						let specActIndex = dataForm.product_stock.findIndex(item => item.pk_id === this
							.params.stockId);
						if (specActIndex > -1) {
							this.specActIndex = specActIndex;
							this.specActItem = {
								...dataForm.product_stock[specActIndex]
							};
							this.dataForm = {
								...dataForm
							}
							this.specNum = this.dataForm.minimum >= this.dataForm.max_num ? this.dataForm
								.max_num : this.dataForm.minimum
							this.initClassName()
							this.$showPopup();
						} else {
							this.$popupClose();
							this.$toast('库存不足');
						}
						this.checkVipPrice();
					}).catch(() => {
						this.$popupClose();
					});
				})
			},
			initClassName() {
				let typeList = []
				if (this.dataForm.stock_name) {
					typeList = JSON.parse(this.dataForm.stock_name)
				}
				if (this.dataForm.type_name && this.dataForm.type_name[0]) {
					this.classList = this.dataForm.type_name.map((name) => {
						return {
							current: null,
							name: name
						}
					})
				} else {
					let classList = []
					for (var index = 0; index < typeList.length; index++) {
						classList.push({
							current: null,
							name: `属性${index}`
						})
					}
					this.classList = [].concat(classList)
				}
				let nameArr = this.dataForm.product_stock[this.specActIndex].name.split('_')
				nameArr.forEach((name, classIndex) => {
					typeList[classIndex].some((typeName, typeIndex) => {
						if (name == typeName) {
							this.classList[classIndex].current = typeIndex
							return true
						} else {
							return false
						}
					})
				})
				this.setTypeList(typeList)
			},
			$specChange(index, classIndex) {
				this.$u.debounce(
					() => {
						if (this.classList[classIndex].current === index) {
							return
						} else if (this.typeList[classIndex][index].disabled) {
							// 缺货
							return
						}
						this.$loading()
						this.classList[classIndex].current = index
						let newName = ''
						this.classList.forEach((classItem, classIndex) => {
							newName += (classIndex == 0 ? '' : '_') + this.typeList[classIndex][classItem
								.current
							].name
						})
						this.specActIndex = this.dataForm.product_stock.findIndex((item) => {
							return item.name == newName
						})
						let obj = {
							...this.dataForm.product_stock[this.specActIndex]
						}
						this.specActItem = {
							...obj
						}
						let num = this.specNum < obj.min_num ? obj.min_num : this.specNum
						this.specNum = num > obj.max_num ? obj.max_num : num
						this.checkVipPrice()
						this.setTypeList()
						this.$hide()
					},
					300,
					true
				);
			},
			setTypeList(list) {
				if (list) {// 初始化
					this.typeList = list.map((newArr, classIndex) => {
						let oldSpecStr = this.specActItem.name
						return newArr.map((name, nameIndex) => {
							let newSpecArr = oldSpecStr.split('_')
							newSpecArr.splice(classIndex, 1, name)
							let hasSome = this.dataForm.product_stock.some((item) => {
								return item.name == newSpecArr.join('_')
							})
							return {
								disabled: !hasSome,
								name: name
							}
						})
					})
				}else{
					// 规格变化
					let typeList = this.typeList
					typeList.forEach((newArr, classIndex) => {
						let oldSpecStr = this.specActItem.name
						return newArr.map((typeNameArr, nameIndex) => {
							let newSpecArr = oldSpecStr.split('_')
							newSpecArr.splice(classIndex, 1, typeNameArr.name)
							let hasSome = this.dataForm.product_stock.some((item) => {
								return item.name == newSpecArr.join('_')
							})
							this.typeList[classIndex][nameIndex].disabled = !hasSome
						})
					})
				}
			},
			$submitProd(type) {
				this.$u.debounce(
					() => {
						if (this.specActIndex < 0) {
							this.$toast('请先选择规格');
							return;
						}
						if (this.specNum <= 0) {
							this.$toast('请先选择数量');
							return;
						}
						this.$popupClose();
						this.$loading();
						this.$resPost(this.detailApi, {
								pk_id: this.dataForm.pk_id
							})
							.then(({
								data
							}) => {
								if (!data.pk_id) return Promise.reject();
								if (type === 'buy') {
									this.$hide();
									this.$submit();
								} else if (type === 'cart') {
									this.$addCartByApi();
								}
							})
							.catch(() => {
								this.$hide();
								this.$toast('商品已下架');
							});
					},
					500,
					true
				);
			},

			onPreviewImage(current) {
				if (!current) return;
				wx.previewImage({
					current,
					urls: [current],
				});
			},

			//
			$submit() {
				let specActItem = {
					...this.specActItem
				};
				if (this.showVip && this.specActItem.vip_price) {
					specActItem.amount = this.specActItem.vip_price;
				}
				this.$emit('change', {
					specActIndex: this.specActIndex,
					specActItem: specActItem,
					specNum: this.specNum
				});
			},
			$addCartByApi(params = {}, errMsg = '添加失败,库存不足') {
				let num = this.specNum;
				if (this.type === '1') num = this.$getCanUseNum();
				if (num === 0) return;

				this.addProdToCart({
						product_id: this.dataForm.pk_id,
						price: this.specActItem.amount,
						name: this.specActItem.name,
						stock_id: this.specActItem.pk_id,
						num,
						...params
					})
					.then(() => {
						this.$hide();
						this.$toast('已加入购物车');
					})
					.catch(() => {
						this.$hide();
						this.$toast(errMsg);
					});
			},
			$getCanUseNum() {
				if (this.params.stockId === this.specActItem.pk_id) {
					return this.specNum - this.params.num;
				} else {
					let cartStock = this.vuex_cart_list.find(item => item.attr_id === this.specActItem.pk_id);
					if (cartStock) {
						return this.specNum - cartStock.num;
					} else {
						return this.specNum;
					}
				}
			},
			$loadProd(isCart = false) {
				return new Promise((resolve, reject) => {
					if (!this.params.prodId) {
						this.$toast('未获取到产品信息');
						return;
					}
					this.$loading();
					this.$resPost('GetProductDetailed', {
							pk_id: this.params.prodId
						})
						.then(({
							data
						}) => {
							if (!data.pk_id) return Promise.reject();
							this.$hide();
							data.product_stock = formatStockList(data.product_stock, isCart, data.minimum);
							if (data.product_stock.length > 0) {
								this.$hide();
								resolve(data);
							} else {
								this.$toast('库存不足');
								reject();
							}
						})
						.catch(() => {
							this.$toast('未获取到产品信息');
							reject();
						});
				});
			},
			checkVipPrice() {
				if (this.dataForm.type == 1) {
					if (
						(this.vuex_user.type == 1 && this.vuex_user.level_name && this.vuex_user.level_name != '普通会员') ||
						(this.vuex_user.type == 2 && this.dataForm.product_stock[this.specActIndex].threelevel > 0) ||
						(this.vuex_user.type == 4 && this.dataForm.product_stock[this.specActIndex].threelevel > 0)
					) {
						this.showVip = true;
					} else {
						this.showVip = false;
					}
				}
			},
			judgeVipPrice() {
				if (this.dataForm.type == 1) {
					if (
						(this.vuex_user.type == 1 && this.vuex_user.level_name && this.vuex_user.level_name != '普通会员') ||
						(this.vuex_user.type == 2 && this.vuex_user.threelevel > 0) ||
						(this.vuex_user.type == 4 && this.vuex_user.threelevel > 0)
					) {
						this.$emit('vipChange');
					}
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.goods-spec-box {
		width: 100%;
		padding: 24rpx 24rpx 0;
		display: flex;
		flex-direction: column;

		.prod-info {
			width: 100%;
			display: flex;
			align-items: center;
			padding-bottom: 16rpx;

			.prod-img {
				position: relative;
				width: 148rpx;
				height: 148rpx;
				margin-right: 20rpx;
				border-radius: 12rpx;
				overflow: hidden;

				.no_bg {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background-color: rgba(0, 0, 0, 0.4);
				}

				.no_prod {
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					width: 100rpx;
					height: 100rpx;
					background-color: rgba(0, 0, 0, 0.6);
					text-align: center;
					color: #fff;
					border-radius: 50%;
					overflow: hidden;

					.no_box {
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
						font-size: 20rpx;
						white-space: nowrap;
					}
				}
			}


			.prod-right {
				flex: 1;
				height: 100%;
				overflow: hidden;

				.prod-price {
					font-size: 28rpx;
					color: var(--price);
				}
			}
		}


		.spec_scroll {
			max-height: 550rpx;
			flex: 1;
			overflow: hidden;

			.spec_main {
				min-height: 300rpx;
			}

			.spec_box {
				margin-top: 10rpx;

				.spec_title {
					color: #000;
					padding: 20rpx 0 20rpx;
					border-top: 2rpx solid #F2F2F0;
				}

				.prod-spec-list {
					width: 100%;
					display: flex;
					flex-wrap: wrap;

					.prod-spec-item {
						min-width: 160rpx;
						max-width: 100%;
						padding: 0 30rpx;
						height: 52rpx;
						border-radius: 26rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 24rpx;
						color: #666666;
						margin: 0 20rpx 20rpx 0;
						position: relative;
						&.disabled{
							background-color: #eee;
							&::after {
								border: 1rpx solid #eee;
							}
						}
						.post_dis{
							position: absolute;
							padding: 2rpx 10rpx;
							top: -16rpx;
							right: -24rpx;
							background-color: #cbcbcb;
							border-top-left-radius: 10rpx;
							border-bottom-right-radius: 10rpx;
							color: #fff;
							z-index: 10;
							font-size: 20rpx;
						}
						&::after {
							content: '';
							width: 199.8%;
							height: 199.7%;
							border-radius: 52rpx;
							border: 1rpx solid #666666;
							position: absolute;
							top: 0;
							left: 0;
							transform: scale(0.5, 0.5);
							pointer-events: none;
							transform-origin: 0 0;
						}
					}

					.prod-spec-act {
						background-color: var(--color);
						color: #ffffff;

						&::after {
							border: none;
						}
					}
				}
			}

		}

		.buy_num {
			border-top: 2rpx solid #f2f2f2;
			margin: 20rpx 0 40rpx;
			padding-top: 20rpx;
			font-size: 28rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.sub-bottom {
			width: 100%;
			height: 100rpx;
			display: flex;
			align-items: center;
			box-sizing: border-box;

			.goods-action-btn-wrap {
				flex: 1;
				height: 80rpx;
				border-radius: 40rpx;
				overflow: hidden;
				display: flex;

				&.disabled {
					.goods-action-btn {
						background-color: #ddd;
					}
				}

				.goods-action-btn {
					flex: 1;
					height: 100%;
					background-color: #ff8b2e;
					font-size: 30rpx;
					color: #ffffff;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				&.usal .goods-action-btn:last-child {
					background-color: var(--color);
				}
			}
		}

	}
</style>
